<template>
  <div class="category-more">
    <!-- Header组件 -->
    <Header />

    <div class="page-content">
      <!-- 页面标题区域 -->
      <div class="page-header">
        <div class="header-content">
          <div class="header-left">
            <h1 class="title">
              <i class="el-icon-collection"></i>
              {{ category.name || '加载中...' }}
            </h1>
            <p class="description">{{ category.remark || '正在获取分类信息...' }}</p>
          </div>
          <div class="header-right">
            <div class="header-stats">
              <div class="stat-item">
                <i class="el-icon-document"></i>
                <span>{{category.total || 0}} 篇内容</span>
              </div>
              <div class="stat-item">
                <i class="el-icon-view"></i>
                <span>{{category.viewCount || 0}}w 次浏览</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 筛选区域 -->
      <div class="filter-section" v-if="!error && !loading">
        <div class="filter-group">
          <span class="filter-label">排序：</span>
          <div class="filter-options">
            <span v-for="option in sortOptions" :key="option.value"
              :class="['filter-option', { active: currentSort === option.value }]"
              @click="handleSort(option.value)">
              {{ option.label }}
            </span>
          </div>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="content-section" :class="{ 'is-mobile': isMobile }">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <div class="loading-spinner"></div>
          <p>加载中...</p>
        </div>

        <!-- 错误状态 -->
        <EmptyState
          v-else-if="error"
          title="加载失败"
          :description="error"
          :tips="['检查网络连接', '稍后重试']"
          :onBackClick="goBack"
          :onRefreshClick="refresh"

        />

        <!-- 空状态 -->
        <EmptyState
          v-else-if="!loading && !sortedItems.length"
          title="暂无内容"
          description="该分类下暂时没有任何内容"
          :tips="['可以查看其他分类', '稍后再来看看']"
          :onBackClick="goBack"
          :onRefreshClick="refresh"

        />

        <!-- 内容网格 -->
        <template v-else>
          <div class="grid-container">
            <content-card
              v-for="(item, index) in sortedItems"
              :key="item.id"
              :item="item"
              @click="handleCardClick(item)"
              @like="handleLike(item)"
              @imageLoad="handleImageLoad(index)"
            />
          </div>

          <!-- 加载更多 -->
          <div v-if="!loading && hasMore" class="load-more" @click="loadMore">
            <div class="load-more-content">
              <svg class="load-more-icon" viewBox="0 0 24 24" width="16" height="16">
                <circle class="circle-bg" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" fill="none"/>
                <path class="arrow" d="M12 8v8M8 13l4 3 4-3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
              <span class="load-more-text">加载更多内容</span>
            </div>
          </div>

          <!-- 无更多内容 -->
          <div v-if="!hasMore && sortedItems.length > 0" class="no-more">
            <div class="no-more-content">
              <div class="line"></div>
              <span>我也是有底线的 ~</span>
              <div class="line"></div>
            </div>
          </div>
        </template>
      </div>
    </div>
    <SideMenu />
    <!-- Footer组件 -->
    <Footer />
  </div>
</template>

<script>
import Header from '@/components/layout/Header.vue'
import Footer from '@/components/layout/Footer.vue'
import ContentCard from '@/components/common/ContentCard.vue'
import SideMenu from "@/components/SideMenu.vue";
import EmptyState from '@/components/EmptyState.vue';
import { getCategoryById } from '@/api/portalAPI'

// 简单的防抖函数实现
function debounce(fn, delay) {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

export default {
  name: 'CategoryMore',
  components: {
    SideMenu,
    Header,
    Footer,
    ContentCard,
    EmptyState
  },
  data() {
    return {
      category: {
        name: '',
        remark: '',
        articleList: [],
        viewCount: 0,
        total: 0
      },
      params: {
        categoryId: this.$route.params.id,
        pageNo: 1,
        pageSize: 8
      },
      currentSort: 'newest',
      sortOptions: [
        { label: '最新', value: 'newest' },
        { label: '推荐', value: 'recommended' },
        { label: '最热', value: 'hottest' }
      ],
      loading: false,
      error: null,
      hasMore: true,
      isMobile: false,
      sortedItems: []
    }
  },
  watch: {
    '$route'(to, from) {
      if (to.params.id !== from.params.id) {
        this.resetState()
        this.loadCategoryData()
      }
    }
  },
  created() {
    // 初始化检查移动端
    this.checkMobile()
    // 创建防抖函数
    this.debouncedCheckMobile = debounce(() => {
      this.checkMobile()
    }, 250)
    // 添加窗口大小改变监听
    window.addEventListener('resize', this.debouncedCheckMobile)
  },
  mounted() {
    this.loadCategoryData()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.debouncedCheckMobile)
  },
  methods: {
    // 重置状态
    resetState() {
      this.category = {
        name: '',
        remark: '',
        articleList: [],
        viewCount: 0,
        total: 0
      }
      this.params.pageNo = 1
      this.error = null
      this.hasMore = true
      this.sortedItems = []
    },
    goBack() {
      this.$router.push('/'); // 返回首页
    },
    refresh() {
      this.resetState()
      this.loadCategoryData()
    },
    async handleSort(value) {
      if (this.currentSort === value) return
      this.currentSort = value
      this.updateSortedItems()
    },
    handleCardClick(item) {
      // 处理卡片点击，跳转到详情页
      this.$router.push(`/detail/${item.id}`)
    },
    handleLike(item) {
      const index = this.category.articleList.findIndex(i => i.id === item.id)
      if (index !== -1) {
        const article = this.category.articleList[index]
        this.$set(article, 'liked', !article.liked)
        article.likeCount = article.liked
          ? article.likeCount + 1
          : article.likeCount - 1
        // 更新排序后的列表
        this.updateSortedItems()
      }
    },
    handleImageLoad(index) {
      if (this.sortedItems[index]) {
        this.$set(this.sortedItems[index], 'loaded', true)
      }
    },
    async loadMore() {
      if (this.loading || !this.hasMore) return
      this.params.pageNo += 1
      await this.loadCategoryData(true)
    },
    async loadCategoryData(isLoadMore = false) {
      if (this.loading) return

      this.loading = true
      this.error = null

      try {
        const { code, data, msg } = await getCategoryById(this.params)

        if (code === 0 && data) {
          if (!isLoadMore) {
            // 首次加载或刷新
            this.category = {
              name: data.name,
              remark: data.remark,
              articleList: data.articleList || [],
              viewCount: data.viewCount,
              total: data.total
            }
          } else {
            // 加载更多
            this.category.articleList.push(...(data.articleList || []))
          }

          // 更新是否有更多数据
          this.hasMore = this.category.articleList.length < this.category.total

          // 更新排序后的列表
          this.updateSortedItems()
        } else {
          throw new Error(msg || '加载失败，请稍后重试')
        }
      } catch (error) {
        console.error('加载分类数据失败:', error)
        this.error = error.message || '加载失败，请稍后重试'
      } finally {
        this.loading = false
      }
    },
    updateSortedItems() {
      const sorted = [...this.category.articleList]

      switch (this.currentSort) {
        case 'hottest':
          sorted.sort((a, b) => b.viewCount - a.viewCount)
          break
        case 'recommended':
          sorted.sort((a, b) => b.likeCount - a.likeCount)
          break
        default:
          // 最新排序，使用原始顺序
          break
      }

      this.sortedItems = sorted
    },
    checkMobile() {
      this.isMobile = window.innerWidth <= 768
    }
  }
}
</script>

<style scoped>
.category-more {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-content {
  flex: 1;
  background: var(--bg-color);
  padding-bottom: 40px;
}

.page-header {
  background: var(--card-bg);
  margin-bottom: 20px;
  border-bottom: 1px solid var(--border-color);
}

.header-content {
  max-width: var(--container-width);
  margin: 0 auto;
  padding: 30px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-left {
  max-width: 70%;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-color);
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.title i {
  color: var(--primary-color);
  font-size: 24px;
}

.description {
  font-size: 14px;
  color: var(--secondary-color);
  line-height: 1.6;
  max-width: 600px;
}

.header-right {
  display: flex;
  align-items: center;
}

.header-stats {
  display: flex;
  gap: 20px;
  padding: 10px 20px;
  background: var(--bg-color);
  border-radius: 8px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--text-color);
  font-size: 14px;
}

.stat-item i {
  color: var(--primary-color);
  font-size: 16px;
}

.filter-section {
  max-width: var(--container-width);
  margin: 0 auto 20px;
  padding: 0 20px;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 15px;
  background: var(--card-bg);
  padding: 15px 20px;
  border-radius: 8px;
  border: 1px solid var(--border-color);
}

.filter-label {
  color: var(--text-color);
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 5px;
}

.filter-label i {
  font-size: 16px;
  color: var(--primary-color);
}

.filter-options {
  display: flex;
  gap: 10px;
}

.filter-option {
  padding: 6px 16px;
  border-radius: 4px;
  font-size: 14px;
  color: var(--secondary-color);
  cursor: pointer;
  transition: all 0.3s;
  background: var(--bg-color);
}

.filter-option:hover {
  color: var(--primary-color);
  background: var(--hover-color);
}

.filter-option.active {
  color: white;
  background: var(--primary-color);
}

.content-section {
  max-width: var(--container-width);
  margin: 0 auto;
  padding: 0 20px;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: var(--secondary-color);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid var(--border-color);
  border-top-color: var(--primary-color);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 加载更多按钮样式 */
.load-more {
  grid-column: 1 / -1;
  padding: 40px 0;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.load-more-content {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 12px 28px;
  background: var(--card-bg);
  border: 1px solid var(--border-color);
  border-radius: 25px;
  color: var(--secondary-color);
  font-size: 14px;
  transition: all 0.3s;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.load-more:hover .load-more-content {
  color: var(--primary-color);
  border-color: var(--primary-color);
  background: linear-gradient(to right, var(--hover-color), var(--card-bg));
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.load-more-text {
  margin-left: 8px;
  font-weight: 500;
}

.load-more-icon {
  transition: all 0.3s;
  width: 20px;
  height: 20px;
}

.circle-bg {
  opacity: 0.2;
}

.arrow {
  transform-origin: center;
  transition: transform 0.3s;
}

.load-more:hover .load-more-icon {
  animation: bounce 1s infinite;
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(3px); }
}

/* 没有更多数据提示样式 */
.no-more {
  grid-column: 1 / -1;
  text-align: center;
  padding: 40px 0;
  color: var(--secondary-color);
  font-size: 14px;
}

.no-more-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
}

.line {
  width: 60px;
  height: 1px;
  background: linear-gradient(to right, transparent, var(--border-color), transparent);
}

/* 响应式布局 */
@media (max-width: 1400px) {
  .grid-container {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 1200px) {
  .grid-container {
    grid-template-columns: repeat(3, 1fr);
  }

  .title {
    font-size: 24px;
  }

  .description {
    font-size: 14px;
  }
}

@media (max-width: 992px) {
  .grid-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }

  .title {
    font-size: 24px;
  }

  .description {
    font-size: 14px;
  }
}

@media (max-width: 768px) {
  .header-content {
    padding: 20px 15px;
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .header-left {
    max-width: 100%;
  }

  .title {
    font-size: 20px;
    margin-bottom: 8px;
  }

  .title i {
    font-size: 20px;
  }

  .description {
    font-size: 13px;
  }

  .header-right {
    width: 100%;
  }

  .header-stats {
    width: 100%;
    padding: 8px 15px;
    justify-content: space-around;
  }

  .filter-section {
    padding: 0 15px;
  }

  .filter-group {
    padding: 12px 15px;
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .filter-options {
    width: 100%;
    overflow-x: auto;
    padding-bottom: 4px;
    -webkit-overflow-scrolling: touch;
  }

  .filter-option {
    padding: 4px 12px;
    font-size: 13px;
    white-space: nowrap;
  }

  .content-section {
    padding: 0 15px;
  }

  .content-section.is-mobile .grid-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
  }

  .loading-container {
    padding: 20px 0;
  }

  .load-more {
    padding: 30px 0;
  }

  .load-more-content {
    padding: 10px 24px;
    font-size: 13px;
  }

  .load-more-icon {
    width: 18px;
    height: 18px;
  }

  .no-more {
    padding: 30px 0;
    font-size: 13px;
  }

  .line {
    width: 40px;
  }
}

@media (max-width: 480px) {
  .content-section.is-mobile .grid-container {
    gap: 8px;
  }
}

/* 错误状态容器 */
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  padding: 40px 20px;
  text-align: center;
  background: var(--card-bg);
  border-radius: 12px;
  margin: 20px 0;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .error-container {
    min-height: 300px;
    padding: 30px 15px;
    margin: 15px 0;
  }
}

@media (max-width: 480px) {
  .error-container {
    min-height: 250px;
    padding: 20px 12px;
    margin: 10px 0;
  }
}
</style>
